package com.jian.mall.produce.service.impl;

import com.jian.mall.common.to.SkuReductionTo;
import com.jian.mall.common.to.SpuBoundTo;
import com.jian.mall.common.utils.R;
import com.jian.mall.produce.entity.*;
import com.jian.mall.produce.feign.CouponFeignService;
import com.jian.mall.produce.service.*;
import com.jian.mall.produce.vo.SaleItemVo;
import com.jian.mall.produce.vo.SpuSaveVo;
import com.jian.mall.produce.vo.spusave.Attr;
import com.jian.mall.produce.vo.spusave.BaseAttrs;
import com.jian.mall.produce.vo.spusave.Images;
import com.jian.mall.produce.vo.spusave.Skus;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jian.mall.common.utils.PageUtils;
import com.jian.mall.common.utils.Query;

import com.jian.mall.produce.dao.SkuInfoDao;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

@EnableTransactionManagement
@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SpuInfoService spuInfoService;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService attrValueService;
    @Autowired
    private CouponFeignService couponFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        // 1.保存spu的基本信息:pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        Date date = new Date();
        spuInfoEntity.setCreateTime(date);
        spuInfoEntity.setUpdateTime(date);
        spuInfoService.save(spuInfoEntity);
        // 2.保存spu的描述图片:pms_spu_info_desc
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", vo.getDecript()));
        spuInfoDescService.save(spuInfoDescEntity);
        // 3.保存spu的图片集:pms_spu_images
        spuImagesService.saveImages(spuInfoEntity.getId(), vo.getImages());
        // 4.保存spu的规格参数:pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(i -> {
            ProductAttrValueEntity entity = new ProductAttrValueEntity();
            entity.setSpuId(spuInfoEntity.getId());
            entity.setAttrId(i.getAttrId());
            AttrEntity id = attrService.getById(i.getAttrId());
            if (id != null)
                entity.setAttrName(id.getAttrName());
            entity.setQuickShow(i.getShowDesc());
            entity.setAttrValue(i.getAttrValues());
            return entity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(collect);

        // 保存spu优惠信息
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        spuBoundTo.setGrowBounds(vo.getBounds().getGrowBounds());
        spuBoundTo.setBuyBounds(vo.getBounds().getBuyBounds());
        R r = couponFeignService.saveSpuBound(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }

        // 5.保存当前spu对应的sku信息：
        List<Skus> skus = vo.getSkus();

        skus.forEach(item -> {

            String defaultImage = "";
            List<Images> images = item.getImages();
            for (Images image : images) {
                if (image.getDefaultImg() == 1) {
                    defaultImage = image.getImgUrl();
                    break;
                }
            }

            // 5.1 sku的基本信息:pms_sku_info
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(item, skuInfoEntity);
            skuInfoEntity.setBrandId(vo.getBrandId());
            skuInfoEntity.setCatalogId(vo.getCatalogId());
            skuInfoEntity.setSaleCount(0L);
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            skuInfoEntity.setSkuDefaultImg(defaultImage);
            skuInfoService.save(skuInfoEntity);
            // 5.2 sku的图片信息:pms_sku_images
            Long skuId = skuInfoEntity.getSkuId();
            List<SkuImagesEntity> imagesEntityList = images.stream().map(img -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                skuImagesEntity.setSkuId(skuId);
                skuImagesEntity.setImgUrl(img.getImgUrl());
                skuImagesEntity.setDefaultImg(img.getDefaultImg());
                skuImagesEntity.setImgSort(0);
                return skuImagesEntity;
            }).filter(f -> StringUtils.isNotEmpty(f.getImgUrl())).collect(Collectors.toList());
            skuImagesService.saveBatch(imagesEntityList);

            // 5.3 sku的销售属性信息:pms_sku_sale_attr_value
            List<Attr> attr = item.getAttr();
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(i1 -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(i1, skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(skuId);
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());
            attrValueService.saveBatch(skuSaleAttrValueEntities);

            // 5.4 sku的优惠、满减等信息;sms_sku_ladder sms_sku_full_reduction...
            SkuReductionTo reductionTo = new SkuReductionTo();
            BeanUtils.copyProperties(item, reductionTo);
            reductionTo.setSkuId(skuId);
            R skuR = couponFeignService.saveSkuBound(reductionTo);
            if (skuR.getCode() != 0) {
                log.error("远程保存sku优惠信息失败");
            }
        });
    }

    @Override
    public PageUtils queryPageCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(w -> w.like("sku_name", key).or().eq("sku_id", key));
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !brandId.equals("0")) {
            wrapper.eq("brand_id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !catelogId.equals("0")) {
            wrapper.eq("catalog_id", catelogId);
        }

        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            wrapper.ge("price", min);
        }
        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max) && !max.equals("0")) {
            wrapper.le("price", max);
        }

        IPage<SkuInfoEntity> page = this.page(new Query<SkuInfoEntity>().getPage(params), wrapper);

        return new PageUtils(page);

    }

    @Override
    public List<SaleItemVo.SkuItemSaleAttr> selectSaleAttrValue(Long spuId) {

        return baseMapper.selectSaleAttrValue(spuId);
    }
}